import React, { memo } from "react";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { Button, Input, Form, Radio, Space, Toast, NavBar } from "antd-mobile";
import jobPicPath from "@/assets/img/logo.png";
import { RegisterWrapper } from "./style.js";
import { setUserInfo } from "@/store/modules/user";
import store from "@/store/index.js";
import { isNameRepeat } from "@/service/user.js";

const Register = memo((props) => {
  const dispath = useDispatch();
  const navigate = useNavigate();

  function finish(e) {
    let confirmPwd = e.confirmPwd;
    let pwd = e.pwd;
    if (pwd !== confirmPwd) {
      Toast.show({
        content: "两次输入的密码不一致",
      });
      return;
    }
    delete e.confirmPwd;

    isNameRepeat({ user: e.user })
      .then((res) => {
        dispath(setUserInfo(e));
        navigate(store.getState().user.redirectTo);
      })
      .catch((err) => {
        console.log(err);
      });
  }

  let checkName = async function (_, val) {
    try {
      await isNameRepeat({ user: val });
      return Promise.resolve();
    } catch (error) {
      if (error.response.status === 409) {
        return Promise.reject(new Error("用户名已被注册"));
      } else {
        return Promise.reject(new Error("发生了错误"));
      }
    }
  };
  return (
    <RegisterWrapper>
      <div className="title">嘿！ 赶紧注册吧!</div>
      <Form
        layout="horizontal"
        onFinish={finish}
        footer={
          <div className="footer">
            <Button block type="submit" color="primary" size="large">
              下一步
            </Button>
            <Button
              block
              color="primary"
              size="large"
              onClick={() => {
                navigate("/login");
              }}
            >
              去登录
            </Button>
          </div>
        }
      >
        <Form.Item
          name="user"
          label="用户名"
          rules={[{ required: true }, { validator: checkName }]}
        >
          <Input placeholder="请输入用户名"></Input>
        </Form.Item>
        <Form.Item
          name="pwd"
          label="密码"
          rules={[{ required: true }, { type: "string", min: 6 }]}
        >
          <Input placeholder="请输入密码" type="password"></Input>
        </Form.Item>
        <Form.Item
          name="confirmPwd"
          label="确认密码"
          rules={[{ required: true }, { type: "string", min: 6 }]}
        >
          <Input placeholder="请再次输入密码" type="password"></Input>
        </Form.Item>
        <Form.Item name="type" label="选择类型" rules={[{ required: true }]}>
          <Radio.Group>
            <Space direction="vertical">
              <Radio value="boss">招聘者</Radio>
              <Radio value="seeker">求职者</Radio>
            </Space>
          </Radio.Group>
        </Form.Item>
      </Form>
    </RegisterWrapper>
  );
});
export default Register;
